package cn.edu.sdjzu.xg.eagle.service.impl;

import cn.edu.sdjzu.xg.eagle.dao.TeacherDao;
import cn.edu.sdjzu.xg.eagle.entity.ActorType;
import cn.edu.sdjzu.xg.eagle.entity.Teacher;
import cn.edu.sdjzu.xg.eagle.entity.User;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.factory.DaoFactory;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.TeacherService;
import cn.edu.sdjzu.xg.eagle.service.UserService;
import cn.edu.sdjzu.xg.eagle.util.Condition;
import cn.edu.sdjzu.xg.eagle.util.IdUtil;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;
import cn.edu.sdjzu.xg.eagle.util.Pagination;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * @author tg.si@188.com
 * @project xg23
 * @date 2025/3/28
 */
public class TeacherServiceImpl implements TeacherService {
//    static ActorService actorService = null;
    static TeacherDao teacherDao = null;
    static UserService userService = null;
    static {
        try{
            teacherDao = DaoFactory.getDao(TeacherDao.class,"TeacherDaoImpl");
//            actorService = ServiceFactory.getService(ActorService.class, "ActorServiceImpl");
            userService = ServiceFactory.getService(UserService.class, "UserServiceImpl");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *
     * @param teacher
     * @return
     * @throws SQLException
     * @throws BaseException
     * @throws InvocationTargetException
     * 事务：先添加Actor对象，然后用它的id（自增）给Teacher对象的id赋值
     */
    @Override
    public boolean add(Teacher teacher) throws SQLException, BaseException,
            InvocationTargetException {
        Connection connection = null;
        try {
            connection = JdbcHelper.getConn();
            connection.setAutoCommit(false); // 开启事务

            // 使用雪花算法生成Teacher的id
            Long teacherId = IdUtil.getLongId();
            teacher.setId(teacherId);

            // 创建User对象，用户名和密码都取自Teacher的no字段
            User user = new User();
            user.setUsername(teacher.getNo());
            user.setPassword(teacher.getNo());
            // 设置User关联的实际参与者类型为Teacher
            user.setActorType(ActorType.TEACHER);

            // 由于teacher的id已经赋值，可以让actor字段指向teacher对象
            // User对象关联Teacher对象
            user.setActor(teacher);

            // 先添加User对象，因为User的id是数据库自增的,保存到数据库才能得到id
            // 将来都使用应用程序生成id，既适应分布式趋势，持久化操作也简化了
            Integer userId = userService.add(connection, user);
            if (userId == null) {
                throw new BaseException("添加用户失败.");
            }

            // 用新生成的User对象的id来设置User对象的id
            user.setId(userId);

            // Teacher对象关联User对象
            teacher.setUser(user);

            // 再持久化teacher对象，此时它的user字段已经关联了User对象
            boolean isAdded = teacherDao.add(connection, teacher);
            if (!isAdded) {
                throw new BaseException("添加教师失败.");
            }

            connection.commit(); // 提交事务
            return true;
        } catch (SQLException | BaseException | InvocationTargetException e) {
            if (connection != null) {
                connection.rollback(); // 回滚事务
            }
            e.printStackTrace();
            throw new BaseException("数据库操作异常.");
        } finally {
            JdbcHelper.close(connection); // 关闭数据库连接
        }
    }
//    @Override
//    public boolean add(Teacher teacher) throws SQLException, BaseException, InvocationTargetException {
//        Connection connection = JdbcHelper.getConn();
//        connection.setAutoCommit(false);
//        //创建User对象，让User的username和password都取Teacher的no值
//        User user = new User(teacher.getNo(),teacher.getNo());
//        //设置它的关联的实际参与者类型为Teacher
//        user.setActorType(ActorType.TEACHER);
//
//        //获得外部生成的长整型
//        Long actorId = IdUtil.getLongId();
//        //给Teacher的id赋值
//        teacher.setId(actorId);
//        //令user关联带有id的teacher。但teacher不能关联user，因为后者没有id。
//        user.setActor(teacher);
//
//        //持久化User,此时因为teacher已经获得了id，故能够写入actor_id（注意此时未持久化Teacher对象）
//        Integer userId = userService.add(connection, user);
//
//        //user的id与赋值
//        user.setId(userId);
//        //teacher关联user，以便持久化teacher时写入
//        teacher.setUser(user);
//        //持久化Teacher，Teacher表中可以保存user_id
//        boolean isAdded = teacherDao.add(connection, teacher);
//        connection.setAutoCommit(true);
//        JdbcHelper.close(connection);
//        return isAdded;
//    }

    @Override
    public Teacher find(Long id) throws SQLException, BaseException, InvocationTargetException {
        Connection connection = JdbcHelper.getConn();
        Teacher teacher = this.find(connection, id);
        JdbcHelper.close(connection);
        return teacher;
    }

    @Override
    public Teacher find(Connection connection, Long id) throws SQLException, BaseException, InvocationTargetException {
        return teacherDao.find(connection, id);
    }

    @Override
    public Collection<Teacher> findAll(List<Condition> conditionList, Pagination pagination) throws SQLException, BaseException, InvocationTargetException {
        //获得连接以便完成可能的事务操作
        Connection connection = JdbcHelper.getConn();
        Collection<Teacher> teachers = teacherDao.findAll
                (connection, conditionList, pagination);
        JdbcHelper.close(connection);
        return teachers;
    }
}
